import { Button, Input, Layout } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useScrollToBottom } from './hooks/useScrollToBottom';
import { Message } from './component/Message/Message';
import { Socket, io } from 'socket.io-client';
interface MessageState {
  text: string;
  user: string;
  isFromSelf: boolean;
}

export function Content() {
  const [curText, setCurtext] = useState('');
  const messageListContentRef = useScrollToBottom<HTMLDivElement>();
  const [messageList, setMessageList] = useState<MessageState[]>([]);
  const ioRef = useRef<Socket>();
  function sendMessage() {
    if (!curText) return;
    setCurtext('');
    ioRef.current?.emit('message', {
      text: curText
    });
    // setMessageList([{ isFromSelf: true, user: 'me', text: curText }].concat(...messageList));
  }

  useEffect(() => {
    const socket = io('http://localhost:3000/meeting-room', {
      query: {
        id: Math.random().toFixed(4)
      },
      transports: ['websocket']
    });
    socket.on('connect', () => {
      ioRef.current = socket;
      console.log('连接成功');
    });
    socket.on('message', (data) => {
      console.log(data);
    });
  }, []);

  return (
    <Layout.Content>
      <div className="message-list" ref={messageListContentRef}>
        {messageList.map((item) => {
          return <Message text={item.text} username={item.user} onRight={false} />;
        })}
      </div>

      <div className="message-input">
        <Input.TextArea
          style={{
            height: '100%'
          }}
          onPressEnter={sendMessage}
          value={curText}
          onChange={(e) => {
            setCurtext(e.target.value);
          }}
        />
        <Button className="message-send" type="primary" onClick={sendMessage}>
          发送
        </Button>
      </div>
    </Layout.Content>
  );
}
